<template>
  <div class="video-player-container">
    <el-page-header @back="goBack" title="返回课程">
      <template #content>
        <h1>{{ chapterInfo.title }}</h1>
      </template>
    </el-page-header>
    
    <div class="video-wrapper">
      <!-- 使用Video.js播放器 -->
      <video
        ref="videoPlayer"
        controls
        autoplay
        class="video-js"
      >
        <source :src="videoUrl" type="video/mp4">
        您的浏览器不支持HTML5视频
      </video>
      
      <!-- 视频信息 -->
      <div class="video-info">
        <h2>{{ chapterInfo.title }}</h2>
        <p class="duration">时长: {{ formatDuration(chapterInfo.duration) }}</p>
        <p class="description">{{ chapterInfo.description }}</p>
      </div>
      
      <!-- 导航按钮 -->
      <div class="navigation-buttons">
        <el-button 
          v-if="prevChapter" 
          @click="goToChapter(prevChapter)"
        >
          <el-icon><ArrowLeft /></el-icon> 上一节
        </el-button>
        
        <el-button 
          type="primary" 
          @click="markAsCompleted"
          v-if="!isCompleted"
        >
          标记为已完成
        </el-button>
        
        <el-button 
          v-if="nextChapter" 
          type="primary" 
          @click="goToChapter(nextChapter)"
        >
          下一节 <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import axios from '@/utils/request'

const route = useRoute()
const router = useRouter()
const videoPlayer = ref(null)
const isCompleted = ref(false)

// 获取路由参数
const courseId = route.params.courseId
const chapterId = route.params.chapterId

// 视频数据
const videoUrl = ref('')
const chapterInfo = ref({
  title: '',
  description: '',
  duration: 0,
  videoUrl: ''
})

// 获取章节信息
const fetchChapterInfo = async () => {
  try {
    const response = await axios.get(`/api/courses/${courseId}/chapters/${chapterId}`)
    chapterInfo.value = response.data
    videoUrl.value = response.data.videoUrl
    
    // 记录学习进度
    await recordLearningProgress()
  } catch (error) {
    ElMessage.error('获取章节信息失败')
    console.error(error)
  }
}

// 记录学习进度
const recordLearningProgress = async () => {
  try {
    await axios.post(`/api/learning/progress`, {
      courseId,
      chapterId,
      userId: localStorage.getItem('userId')
    })
  } catch (error) {
    console.error('记录学习进度失败:', error)
  }
}

// 标记为已完成
const markAsCompleted = async () => {
  try {
    await axios.put(`/api/learning/progress`, {
      courseId,
      chapterId,
      status: 'completed'
    })
    isCompleted.value = true
    ElMessage.success('已标记为完成')
  } catch (error) {
    ElMessage.error('标记失败')
  }
}

// 返回课程详情
const goBack = () => {
  router.push(`/course-detail/${courseId}`)
}

// 格式化时长
const formatDuration = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs < 10 ? '0' : ''}${secs}`
}

// 获取相邻章节
const prevChapter = computed(() => route.query.prevChapter)
const nextChapter = computed(() => route.query.nextChapter)

// 跳转到指定章节
const goToChapter = (chapter) => {
  router.push({
    name: 'VideoPlayer',
    params: {
      courseId,
      chapterId: chapter.id
    },
    query: {
      prevChapter: route.query.currentChapter,
      nextChapter: route.query.nextChapter
    }
  })
}

onMounted(() => {
  fetchChapterInfo()
})

onBeforeUnmount(() => {
  // 清理视频播放器
  if (videoPlayer.value) {
    videoPlayer.value.pause()
  }
})
</script>

<style scoped>
.video-player-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.video-wrapper {
  margin-top: 20px;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

video {
  width: 100%;
  height: 600px;
  background: #000;
}

.video-info {
  padding: 20px;
  color: #333;
}

.video-info h2 {
  margin-bottom: 10px;
}

.duration {
  color: #666;
  font-size: 14px;
}

.description {
  margin-top: 15px;
  line-height: 1.6;
}

.navigation-buttons {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  border-top: 1px solid #eee;
}

@media (max-width: 768px) {
  video {
    height: 300px;
  }
}
</style>